/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ps.server.componentes;

import com.ps.server.CheckNodeMutable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Ricardo
 */
public class nodeSelectionTreeListener extends MouseAdapter {

    JTree tree;

    public nodeSelectionTreeListener(JTree tree) {
        this.tree = tree;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        int row = tree.getRowForLocation(x, y);
        TreePath path = tree.getPathForRow(row);
        //TreePath  path = tree.getSelectionPath();
        if (path != null) {
            CheckNodeMutable node = (CheckNodeMutable) path.getLastPathComponent();
            boolean isSelected = !(node.isSelected());
            node.setSelected(isSelected);
            if (node.getSelectionMode() == CheckNodeMutable.DIG_IN_SELECTION) {
                if (isSelected) {
                    tree.expandPath(path);
                } else {
                    tree.collapsePath(path);
                }
            }
            ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
            // I need revalidate if node is root.  but why?
            if (row == 0) {
                tree.revalidate();
                tree.repaint();
            }
        }
    }
}
